package com.maycurobj.controller.maycur;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maycurobj.pojo.*;
import com.maycurobj.service.impl.DingTalkService;
import com.maycurobj.service.impl.MaycurBudgetService;
import com.maycurobj.service.impl.MaycurService;
import com.maycurobj.service.impl.MeetingService;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 每刻-业务中台 中台接口
 */
@Controller
@RequestMapping("/maycurpivot")
@Slf4j
public class MaycurPivotController {

    @Autowired
    private MaycurService maycurService;

    @Autowired
    private MeetingService meetingService;

    @Autowired
    private MaycurBudgetService maycurBudgetService;

    @Autowired
    private DingTalkService dingTalkService;

    /**
     * OA流程 推送 物品领用 from oa流程
     */
    @PostMapping("/pushWPLYwf")
    @ResponseBody
    public Map<String, Object> pushWPLYFromWF(@RequestBody MayCurWPLYInfo maint) {
        log.info("物品领用推送--接受OA对象：{}", JSONObject.toJSONString(maint));

        //推送
        try {
            Map<String, Object> returnObj = this.maycurService.addReceiveReimburse(maint);
            log.info("物品领用--请求结果:{}", JSONObject.toJSONString(returnObj));
            return returnObj;
        } catch (Exception ex) {
            ex.printStackTrace();
            this.dingTalkService.pushDingMsg("推送物品领用error：" + JSONObject.toJSONString(maint), new String[]{
                    "15267167276"});
            return null;
        }
    }

    /**
     * 会议 推送 物品领用
     */
    @PostMapping("/pushMayCurMeetingWP")
    @ResponseBody
    public Map<String, Object> pushMayCurMeetingWP(@RequestBody MayCurMeetingWPMain maint) {
        log.info("物品领用推送：{}", JSONObject.toJSONString(maint));
        try {
            Map<String, Object> returnMap = this.meetingService.createReceiveWP(maint);
            return returnMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    /**
     * 会议 推送 对公付款
     */
    @PostMapping("/pushMayCurMeetingFK")
    @ResponseBody
    public Map<String, Object> pushMayCurMeetingFK(@RequestBody MayCurMeetingFKMain maint) {
        log.info("对公付款推送：{}", JSONObject.toJSONString(maint));
        try {
            Map<String, Object> returnMap = this.meetingService.createReceiveFK(maint);
            return returnMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    /**
     * 会议 推送 费用报销
     */
    @PostMapping("/pushMayCurMeetingBX")
    @ResponseBody
    public Map<String, Object> pushMayCurMeetingBX(@RequestBody MayCurMeetingBXMain maint) {
        log.info("费用报销推送：{}", JSONObject.toJSONString(maint));
        try {
            Map<String, Object> returnMap = this.meetingService.createReceiveBX(maint);
            return returnMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    /**
     * 会议 推送 借款申请
     */
    @PostMapping("/pushMayCurMeetingJK")
    @ResponseBody
    public Map<String, Object> pushMayCurMeetingJK(@RequestBody MayCurMeetingJKMain jkMain) {

        try {
            Map<String, Object> returnMap = this.meetingService.createReceipt(jkMain);
            return returnMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 根据预算主体编码查询预算详细信息
     * 仅限当前季度的预算
     * @param orgBizCode：预算主体编码
     * @param subjectBizCode：预算科目编码
     */
    @GetMapping("/getBudget")
    @ResponseBody
    public Map<String, Object> getBudget(String orgBizCode, String subjectBizCode ) {
        if(!orgBizCode.isEmpty()&&!subjectBizCode.isEmpty()){
            try {
                Map<String, Object> returnMap = this.meetingService.getBudget(orgBizCode, subjectBizCode);
                return returnMap;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 获取每刻的公司抬头名称及对应的ID
     */
    @GetMapping("/getCompany")
    @ResponseBody
    public Map<String,Object> getCompany() {
        Map<String,Object> companyMap = new HashMap<>();
        try {
            List<MayCurCompanyDTO> returnList = this.meetingService.getCompany();
            companyMap.put("companyList",returnList);
            return companyMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 获取往来单位列表
     */
    @GetMapping("/getTradingPartner")
    @ResponseBody
    public Map<String,Object> getTradingPartner(int pageNo,int pageSize,String keyword) {
        Map<String,Object> partnerMap = new HashMap<>();
        try {
            List<MayCurMeetingPartnerDTO> returnList = this.meetingService.getTradingPartner(pageNo,pageSize,keyword);
            partnerMap.put("partnerList",returnList);
            return partnerMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 获取往来单位银行账号列表
     */
    @GetMapping("/getTradingPartnerAccount")
    @ResponseBody
    public Map<String,Object> getTradingPartnerAccount(String bizCodes) {
        Map<String,Object> partnerAccountMap = new HashMap<>();
        try {
            List<MayCurMeetingPartnerAccountDTO> returnList = this.meetingService.getTradingPartnerAccount(bizCodes);
            partnerAccountMap.put("partnerAccountList",returnList);
            return partnerAccountMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 获取客户档案列表
     */
    @GetMapping("/getCustomerList")
    @ResponseBody
    public Map<String,Object> getCustomerList(int pageNum,int pageSize,String keyword) {
        Map<String,Object> customerMap = new HashMap<>();
        try {
            List<MayCurMeetingCustomerDTO> returnList = this.meetingService.getCustomerList(pageNum,pageSize,keyword);
            customerMap.put("customerList",returnList);
            return customerMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    /**
     * 流程扣减预算
     * @param action
     * @return
     */
    @PostMapping("/wplyOccupy")
    @ResponseBody
    public Map<String,Object> wplyOccupy(@Validated @RequestBody MayCurWPLYAction action) {
        log.info("预选占用对象:{}", JSONObject.toJSONString(action));
        Map<String, Object> rspmap = new HashMap<>();
        String kemu=convfylx(action.getFeiyonglx());
        String ret=maycurBudgetService.setOccupyBudget(action.getLipinje(), kemu, action.getYusuanzt(), action.getLiuchengbh());
        if (StringUtils.isBlank(ret)) {
            rspmap.put("success", false);
            rspmap.put("msg", "请求每刻预选信息返回异常!!请联系管理员");
            return rspmap;
        }
        JSONObject retJson = JSONObject.parseObject(ret);
        rspmap.put("success", retJson.get("success"));
        rspmap.put("msg", retJson.get("data"));
        return rspmap;
    }


    /**
     * 物品领用的客户信息接口
     */
    @GetMapping("/getCustomer")
    @ResponseBody
    public JSONArray getMayCurCustomer(@RequestParam(value = "name") String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        JSONArray array = null;
        try {
            array = maycurService.getMaycurTrading(name);

        } catch (Exception e) {
            e.printStackTrace();

        }
        return array;
    }

    /**
     * 在每刻自定义档案中 新增客户记录（未分类的）
     * 参数
     * map: name,id,path,sheng
     * @param cus
     * @return
     */
    @PostMapping("/addCustomerToReference")
    @ResponseBody
    public String addMayCurCustomerToReference(@RequestBody Map<String,String> cus) {
        log.info("在每刻自定义档案中 接收报文----->", JSONObject.toJSONString(cus));
        String data="RD211118ZNNJFK0";
        MayCurPartner mayCurPartner = new MayCurPartner();
        mayCurPartner.setParentName(cus.get("path"));
        mayCurPartner.setName(cus.get("name"));
        mayCurPartner.setBusinessCode(cus.get("id"));
        String state=maycurService.pushReferenceDetail(mayCurPartner, data);
        return state;
    }

    /**
     * 在每刻自定义档案中 更新客户记录
     * 参数
     * map: name(客户新名称),id(code),path(省份)
     * @param cus
     * @return
     */
    @PostMapping("/editCustomerToReference")
    @ResponseBody
    public String editMayCurCustomerToReference(@RequestBody Map<String,String> cus) {
        log.info("更新每刻自定义档案中客户信息----->", JSONObject.toJSONString(cus));
        String data="RD211118ZNNJFK0";
        MayCurPartner mayCurPartner = new MayCurPartner();
        mayCurPartner.setParentName(cus.get("path"));
        mayCurPartner.setName(cus.get("name"));
        mayCurPartner.setBusinessCode(cus.get("id"));
        String state=maycurService.pushReferenceDetail(mayCurPartner, data);
        return state;
    }

    /**
     * 获取每刻 预算主体剩余预算
     * 传入对象
     * shenqingrq   申请日期
     * zongjine     总计金额
     * yusuanzt     预算主体
     */
    @PostMapping("/budget")
    @ResponseBody
    public BigDecimal getMaycurBudget(@RequestBody Map<String, Object> map) {

        log.info("预算--获取到的对象{}", JSONObject.toJSONString(map));
        String shenqingrq = map.get("shengqingrq").toString();
        double zongjine = Double.valueOf(map.get("zongjine").toString());
        String yusuanzt = map.get("yusuanzt").toString();
        //预算科目
        String yusuankm = convfylx(map.get("feiyonglx").toString());
        //预算季度
        //判断是否年度预算，如果是年度预算科目，则返回1，否则反回当前季度预算
        int quarterNo =0;
        if (yusuankm.equals("10") || yusuankm.equals("07") && yusuanzt.equals("BU1000")){
            quarterNo = 1;
        }else {
            quarterNo = getQuarterFromDate(shenqingrq);
        }
        log.info("判断是否年度预算{}",quarterNo);
        //返回预算
        BigDecimal bigDecimal = new BigDecimal(0.00);
        //获取用户当前预算
        try {
            if (!shenqingrq.equals("") && !yusuanzt.equals("") && quarterNo != 0) {
                //获取当前用户季度数
                bigDecimal = this.maycurService.getBudget(yusuanzt, yusuankm, shenqingrq, quarterNo);
                log.info("获取到的结果--->{}" + bigDecimal.toString());
                return bigDecimal;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            log.info("错误");
            return bigDecimal;
        }
        return bigDecimal;
    }

    /**
     * 获取每刻 userid 到 phone转换
     *
     * @param map
     * @return
     */
    @ResponseBody
    @PostMapping("/getPhoneNo")
    public String getMaycurUserPhone(@RequestBody Map<String, String> map) {
        String userid = map.get("userid");
        String phone = this.maycurService.getEmployeeDetails(userid);
        return phone;
    }

    /**
     * 获取季度
     */
    public int getQuarterFromDate(String date) {
        if (date == "" || "".equals(date)) {
            return 0;
        }
        try {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date datePar = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(datePar);

            int mouth = datePar.getMonth() + 1;

            if (mouth >= 1 && mouth <= 3) {
                return 1;
            } else if (mouth >= 4 && mouth <= 6) {
                return 2;
            } else if (mouth >= 7 && mouth <= 9) {
                return 3;
            } else if (mouth >= 10 && mouth <= 12) {
                return 4;
            } else {
                return 0;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return 0;
        }
    }

    /**
     * 费用类型转换 OA系统 前端页面转换ID用
     * 0->02
     * 1->07
     * @param
     * @return
     */
    private String convfylx(String s) {
        try {
            if ("0".equals(s)) {
                return "02";
            }else if("1".equals(s)){
                return "07";
            }else if("2".equals(s)){
                return "06";
            }else if ("3".equals(s)){
                return "09";
            }else if ("4".equals(s)){
                return "10";
            }else if ("5".equals(s)){
                return "11";
            }else if ("6".equals(s)){
                return "18";
            }else {
                return "02";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "02";
        }
    }
}
